<?php

namespace App\Service\Video\V1_1_0;

use App\Model\VideoLink;
use App\Service\BaseService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class VideoListService extends BaseService
{
    /**
     * @Inject
     * @var VideoLink
     */
    protected $videoLinkModel;

    /**
     * 返回
     * @var
     */
    private $return;

    /**
     * 主控制器
     * @return array
     */
    public function handle(): array
    {
        $this->return = [
            'total' => 0,
            'total_page' => 0,
            'page' => 0,
            'list' => []
        ];

        $page = $this->request->input('page');
        $limit = 20;

        $this->getListData($page, $limit);

        if (!empty($this->return['list'])){
            $this->pickData();
        }

        return $this->return;
    }

    /**
     * 获取列表数据
     * @param $page
     * @param $limit
     * @return void
     */
    private function getListData($page, $limit): void
    {
        $where[] = ['status', '=', 1];
        $where[] = ['wx_id', '>', 0];

        $this->return['total'] = $this->videoLinkModel->where($where)->count() ?? 0;

        $this->return['total_page'] = (int)ceil($this->return['total'] / $limit);

        $this->return['page'] = (int)$page;

        $this->return['list'] = $this->videoLinkModel
            ->where($where)
            ->offset(((int)$page - 1) * $limit)
            ->limit($limit)
            ->select('title as text_content', 'introduce', 'video_cover', 'video_url', 'xcv_url','wx_info')
            ->orderBy('sort')
            ->get()
            ->toArray();
    }

    /**
     * @return void
     */
    private function pickData()
    {
        foreach ($this->return['list'] as &$one){
            $one['wx_info'] = $one['wx_info'] ? json_decode($one['wx_info'], true) : [];
            $one['link'] = $one['wx_info']['link'] ?? '';
            $one['appid'] = $one['wx_info']['appid'] ?? '';
            $one['original_id'] = $one['wx_info']['original_id'] ?? '';
        }
    }
}